
from astropy import units as u
from netorchestr.envir.base import OModule, OGate, OLink, OMessage, ONet
from netorchestr.envir.clock.timer import ClockTime

class Txc(OModule):
    def __init__(self, name:str):
        super().__init__(name)
        
        clocktime = ClockTime(f"{self.name}Timer")
        clocktime.set_tick_interval(20*u.ms)
        self.add_link(OLink('clocktime', 0*u.ms), clocktime)
        self.add_submodule(clocktime)
        

    def recv_msg(self, msg:"OMessage", gate:"OGate"):
        if msg.sender == f'{self.name}Timer' and self.name == 'tic':
            msg = OMessage(self.scheduler.now, self.name, 'toc', 'tictocMsg', f'{self.scheduler.now}')
            out_gate = [g for g in self.gates if g.name == 'out']
            self.send_msg(msg, out_gate[0])


if __name__ == '__main__':
    net = ONet('Tictoc')
    tic = Txc('tic')
    toc = Txc('toc')
    
    gate_tic = OGate('out', tic)
    gate_toc = OGate('out', toc)
    
    tic.gates[gate_tic] = (OLink('tic-toc', 10.0*u.ms), gate_toc)
    toc.gates[gate_toc] = (OLink('tic-toc', 10.0*u.ms), gate_tic)
    
    net.add_module(tic)
    net.add_module(toc)
    
    net.run(1000*u.ms)



